#coding=utf-8

from ConfigParser import ConfigParser

"""
@Time   : 2022-02-26
@Author : 吕文光
@File   : ConfTool27.py
@Desc   : Python27 读写ini配置文件
"""

class ConfTool(ConfigParser, object):
    """Reader Class for .ini

    Python27版本，读取 windows .ini 配置文件内容
    """

    def __init__(self, file):
        """初始化函数"""

        # TypeError: must be type, not classobj
        super(ConfTool, self).__init__()
        # TypeError: super() takes at least 1 argument (0 given)
        #super().__init__()
        # TypeError: unbound method __init__() must be called
        # with ConfigParser instance as first argument (got nothing instead)
        #ConfigParser.__init__()

        self.inifile = file
        self.readfp(open(file, "r"))

    def get_or_default(self, section, option, default=None):
        """读取ini文件中的参数"""

        if not self.has_section(section):
            return default
        elif not self.has_option(section, option):
            return default
        return self.get(section=section, option=option)

    def to_dict(self):
        """将ini文件中的内容转为字典"""

        _dict = {}
        for section in self.sections():
            # print(dict(conf.items("mysql_conf")))
            _option_dict = dict(conf.items(section=section))
            _dict.update({section: _option_dict})
        return _dict

    def set_and_write(self, section, option, value):
        """马上写入单个配置项"""

        if not self.has_section(section):
            self.add_section(section)

        self.set(section, option, value) # 设置多个值，可连续多次调用 set 然后再 write

        # wb - 写入时每行的末尾只添加 \n，而不是添加 \r\n，这样在记事本中查看时，没有换行
        with open(self.inifile, 'r+') as configfile:
            self.write(configfile)

    def getint(self, section, option, default=0):
        """重写获取指定类型的值  getfloat()/getboolean() 可以用同样的写法增加默认值"""
        if not self.has_section(section):
            return default
        elif not self.has_option(section, option):
            return default
        return super(ConfTool, self).getint(section, option)

def read_ini(self, file, section, option, value, default=None):
    """写入指定文件"""
    pass


def write_ini(self, file, section, option, value):
    """写入指定文件"""
    pass

conf = ConfTool(file="config.ini")

if __name__ == '__main__':
    #conf = ConfTool(file="config.ini")
    # 配置文件中如没有配置mysql登录名user字段，则默认取root
    print(conf.get_or_default("server", "username", "root"))
    print(conf.get_or_default("server", "password", "root"))
    print(conf.to_dict())
    conf.set_and_write("test","key","value")
    print(conf.get_or_default("test", "key", "not value"))
